<template>
  <Drawer
    width="100%"
    placement="right"
    :closable="false"
    :visible="visible"
    :get-container="false"
    :style="{ position: 'absolute' }"
  >
    <Divider orientation="left"
      ><span style="margin-right: 8px; font-weight: bolder">
        <Tag color="blue" v-if="defineType === 'ELEMENT'">{{ defineType }}</Tag>
        <Tag color="pink" v-if="defineType === 'MENU'">{{ defineType }}</Tag>
        <Tag color="purple" v-if="defineType === 'CHILD'">{{ defineType }}</Tag>
        <Tag color="green" v-if="defineType === 'ROOT'">{{ defineType }}</Tag>
        {{ title }}</span
      ></Divider
    >
    <Divider orientation="left"><span style="margin-right: 8px; font-weight: bolder">基本信息</span></Divider>
    <BasicForm @register="registerForm"></BasicForm>
    <Divider orientation="left"><span style="margin-right: 8px; font-weight: bolder">API信息</span></Divider>
    <div v-if="drawerType === 'info' || drawerType === 'edit'">
      <span v-per="'addApi'">
        <Button
          type="primary"
          class="left-2/5 mb-5"
          @click="apiHandler"
          :disabled="drawerType === 'new root' || drawerType === 'new child' || drawerType === 'info'"
          >新增API
        </Button>
      </span>

      <BasicTable @register="registerTable"></BasicTable>
    </div>
    <div class="absolute bottom-3 right-8">
      <Button style="margin-right: 8px; font-weight: bolder" @click="onClose">取消</Button>
      <Button type="primary" style="font-weight: bolder" @click="onSubmit">确定</Button>
    </div>
  </Drawer>
  <ApiModal ref="modalRef" @success="successHandler"></ApiModal>
</template>

<script lang="ts" setup>
/* eslint-disable */
import { Drawer, Button, Divider, Tag } from 'ant-design-vue';
import { nextTick, ref, watch } from 'vue';
import BasicForm from '/@/components/BasicForm/BasicForm.vue';
import BasicTable from '/@/components/BasicTable/BasicTable.vue';
import { useBasicForm } from '/@/components/BasicForm/hooks/useBasicForm';
import { useBasicTable } from '/@/components/BasicTable/hooks/useBasicTable';
import {
  apiColumns,
  menuChange,
  resourceInfoSchema,
  resourceNewSchema,
  resourceSchema,
} from '/@/views/system-mgmt/app-resource-mgmt/form';
import ApiModal from '/@/views/system-mgmt/app-resource-mgmt/apiModal.vue';
import {
  createResource,
  deleteResource,
  getSubResourceList,
  updateResource,
} from '/@/api/system-mgmt/app-resource-mgmt/resource';
import { ResourceParams } from '/@/api/system-mgmt/app-resource-mgmt/model/resourceModel';
import { useTreeData } from '/@/views/system-mgmt/app-resource-mgmt/editData';
import { checkPowerByName } from '/@/utils/permission';

const { getData } = useTreeData();
const modalRef = ref();
const visible = ref(false);
const title = ref();
const drawerType = ref();
const emit = defineEmits(['success']);
const defineType = ref();
const appId = ref();
const [registerForm, { validate, setFieldsValue, resetFields, updateSchema }] = useBasicForm({
  labelWidth: 100,
  showActionButtonGroup: false,
  schemas: resourceSchema,
});

const successHandler = async () => {
  let res: any[] = await getSubResourceList({ id: getData().id });
  let result = [];
  res.forEach((item) => {
    if (item.type === 'API') {
      result.push(item);
    }
  });
  setTableData(result);
};

const handleEdit = async (record: Recordable) => {
  modalRef.value.openModal(record, appId.value, getData().id);
};

const handleDelete = async (record: Recordable) => {
  await deleteResource({ id: record.id });
  await successHandler();
};

const apiHandler = () => {
  modalRef.value.openModal(undefined, appId.value, getData().id);
};

const [registerTable, { setTableData }] = useBasicTable({
  usePagination: true,
  immediate: true,
  columns: apiColumns,
  useSearchForm: false,
  actionColumns: [
    {
      name: '编辑',
      click: handleEdit,
      props: {
        style: { color: '#447b9c', fontWeight: 'bolder', backgroundColor: '' },
        disabled: () => {
          return drawerType.value === 'info' && checkPowerByName('updateInterface') ? true : false;
        },
      },
      ifShow: checkPowerByName('updateInterface'),
    },
    {
      name: '删除',
      click: handleDelete,
      props: {
        style: { color: '#447b9c', fontWeight: 'bolder', backgroundColor: '' },
        disabled: () => {
          return drawerType.value === 'info' && checkPowerByName('deleteInterface') ? true : false;
        },
      },
      ifShow: checkPowerByName('deleteInterface'),
    },
  ],
});

const openDrawer = async (info: any, params: any, type: string, appTempId: string) => {
  drawerType.value = type;
  appId.value = appTempId;

  if (type === 'new root') {
    defineType.value = 'ROOT';
    title.value = info + '新增根资源';
    await updateSchema(resourceNewSchema);
    await updateSchema([
      {
        field: 'parentId',
        dynamicDisabled: true,
        required: false,
      },
    ]);
    await resetFields();
    await setFieldsValue({
      status: 0,
      ifHideMenu: false,
      ifHideChildrenInMenu: false,
      ifHideBreadcrumb: false,
    });
  } else if (type === 'new child') {
    defineType.value = 'CHILD';
    title.value = info + ' - 新增子资源';
    await resetFields();
    await setFieldsValue({ parentId: params });
    await setFieldsValue({ status: 0, ifHideMenu: false, ifHideChildrenInMenu: false, ifHideBreadcrumb: false });
    await updateSchema(resourceNewSchema);
    await updateSchema({
      field: 'parentId',
      dynamicDisabled: true,
      required: true,
    });
  } else if (type === 'info') {
    await resetFields();
    defineType.value = params.node.type;
    title.value = info + ' - 详情';
    await updateSchema(resourceInfoSchema);
    await setFieldsValue(params.node);

    let res: any[] = await getSubResourceList({ id: params.node.id });
    let result = [];
    res.forEach((item) => {
      if (item.type === 'API') {
        result.push(item);
      }
    });
    setTableData(result);
  } else if (type === 'edit') {
    await resetFields();

    defineType.value = getData().type;
    console.log(getData().type);
    title.value = info + ' - 编辑';
    await updateSchema(resourceNewSchema);
    if (defineType.value === 'MENU') {
      await updateSchema(menuChange);
    }
    await setFieldsValue(getData());
    await updateSchema([
      {
        field: 'parentId',
        dynamicDisabled: true,
        required: false,
      },
      {
        field: 'type',
        dynamicDisabled: true,
        required: false,
      },
    ]);

    successHandler();
  }
  visible.value = true;
};

const onSubmit = async () => {
  if (drawerType.value === 'new root' || drawerType.value === 'new child') {
    let params: ResourceParams = await validate();
    params.appId = appId.value;
    createResource(params);
  } else if (drawerType.value === 'edit') {
    let params: ResourceParams = await validate();
    params.appId = appId.value;
    updateResource(params);
  }
  emit('success');
  onClose();
};
const onClose = async () => {
  visible.value = false;
};

defineExpose({ openDrawer, onClose, visible });
</script>
